﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using Me.Prettyprint.Cassandra.Utils;

namespace Me.Prettyprint.Cassandra.Serializers
{
	/// <summary>
    /// Objects that need to be serialized must have [Serializable]
	/// </summary>
    public class ObjectSerializer : AbstractSerializer<object>
    {
        public static ObjectSerializer Instance = new ObjectSerializer();

        public ObjectSerializer()
        {
        }
        public override byte[] ToBytes(object obj)
        {
            var formatter = new BinaryFormatter();
            using (var stream = new MemoryStream())
            {
                formatter.Serialize(stream, obj);
                stream.Seek(0, SeekOrigin.Begin);
                return stream.ToArray();
            } 
        }
        public override Utils.ByteBuffer ToByteBuffer(object obj)
        {
            return new ByteBuffer(ToBytes(obj));
        }
        public override object FromBytes(byte[] bytes)
        {
            var formatter = new BinaryFormatter();
            using (var stream = new MemoryStream(bytes))
            {
                return formatter.Deserialize(stream);
            }
        }
        public override object FromByteBuffer(ByteBuffer buff)
        {
            return FromBytes(buff.GetBuffer());
        }
    }
}
